package com.ssaurel.mysleepquality.sleeptracker

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.ssaurel.mysleepquality.R
import com.ssaurel.mysleepquality.database.SleepDatabase
import com.ssaurel.mysleepquality.databinding.FragmentSleepTrackerBinding

class SleepTrackerFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val binding : FragmentSleepTrackerBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_sleep_tracker,container,false)

        val application = requireNotNull(this.activity).application

        //获取数据源
        val dataSource = SleepDatabase.getInstance(application).sleepDatabaseDao

        //实例viewModelFactory
        val viewModelFactory = SleepTrackerViewModelFactory(dataSource,application)

        //获取ViewModel
        val sleepTrakerViewModel = ViewModelProvider(this,viewModelFactory).get(SleepTrackerViewModel::class.java)

        //绑定生命周期所持有
        binding.setLifecycleOwner(this)

        //绑定ViewModel
        binding.sleepTrackerViewModel = sleepTrakerViewModel

        return binding.root
    }
}